package org.example.c_0_003;

import org.junit.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

/**
 * 线程限流类，在执行期间进行限流，线程数量可能无限多，但是同时执行的线程数量进行控制。
 */
public class T_Semaphore {
    private void m(Semaphore semaphore, CountDownLatch countDownLatch){
        try {
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+"线程开始");
            Thread.sleep(2000L);
            System.out.println(Thread.currentThread().getName()+"线程结束");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            countDownLatch.countDown();
            semaphore.release();
        }

    }

    @Test
    public void test(){
        Semaphore semaphore = new Semaphore(1,true);// 限流为1，公平队列
        CountDownLatch countDownLatch = new CountDownLatch(2);
        new Thread(()->{
            m(semaphore,countDownLatch);
        },"t1").start();
        new Thread(()->{
            m(semaphore,countDownLatch);
        },"t2").start();

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
